package simpleftp.server;

import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * Simple serveur TCP creant des thread pour gerer chaque connexion client.
 * 
 * @author lom
 */
public class FTPServerMain {

	/**
	 * Port d'ecoute.
	 */
	public static final int PORT = 7802;
	/**
	 * Socket serveur d'accueil.
	 */
	private static ServerSocket socketaccueil;
	
	/*
	 * New declaration 
	 */
	private final static double blockingCoefficient = 0.9;
	private final static int numberOfCores = Runtime.getRuntime().availableProcessors();
	private final static int poolSize = (int) (numberOfCores / (1 - blockingCoefficient));
	private static ExecutorService executorPool = Executors.newFixedThreadPool(poolSize);
	private static CompletionService<Void> completionPool = new ExecutorCompletionService<Void>(executorPool);

	public static void main(String argv[]) throws Exception 
	{
		// TODO MAKE IT MULTITHREAD (about 4 lines)
		try {
			
			
			socketaccueil = new ServerSocket(PORT);
			
			FTPServer.setDebug(true);
			
			final List<Future<Void>> MultiServer = new ArrayList<Future<Void>>();
		
			System.out.println("Server up and running.");
			
			while (true) {
				
				FTPServer server = new FTPServer(socketaccueil.accept());
				
				MultiServer.add(completionPool.submit(server));
				
			}
		} finally {
			if (socketaccueil != null) {
				socketaccueil.close();
			}
		}
	}
}